package com.liang.myWebSocketServer;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {

    /**
     * 存储用户会话信息
     */
    private Session session;

    /**
     * 存储用户id
     */
    private Long  userId;

    /**
     * 存储每个用户的WebSocketServer
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();

    /**
     * 存储用户连接信息
     */
    private static ConcurrentHashMap<Long, Session> sessionPool = new ConcurrentHashMap<Long, Session>();

    /**
     * 连接成功调用
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") Long userId) {
        try {
            this.session = session;
            this.userId = userId;
            webSockets.add(this);
            sessionPool.put(userId, session);
            System.out.println(("【websocket消息】有新的连接，总数为:" + webSockets.size()));
        } catch (Exception e) {
        }
    }

    /**
     * 连接断开调用
     */
    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            sessionPool.remove(this.userId);
            System.out.println(("【websocket消息】连接断开，总数为:" + webSockets.size()));
        } catch (Exception e) {
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message) {
//        logger.info("【websocket消息】收到客户端消息:" + message);
    }

    /**
     * 发送错误时的处理
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println(("用户错误,原因:" + error.getMessage()));
        error.printStackTrace();
    }
    /**
     * 此为广播消息
     */
    public void sendAllMessage(String message) {
        System.out.println(("【websocket消息】广播消息:" + message));
        for (WebSocketServer webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 此为单点消息
     */
    public void sendOneMessage(Long userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                System.out.println(("【websocket消息】 单点消息:" + message));
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 此为单点消息(多人)
     */
    public void sendMoreMessage(Long[] userIds, String message) {
        for (Long userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    System.out.println(("【websocket消息】 单点消息:" + message));
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
